import 'dart:convert';
import 'package:convert/convert.dart';

import 'package:dio/dio.dart';
import 'package:crypto/crypto.dart' as crypto;
import 'package:http/http.dart' as http;
import 'package:flutter_reader/tools/globals.dart' as globals;

const testURL = 'http://appapi.98nice.cn/api';
class LoginDao{

  static Future getAuthCode(int dateError, String uuid, int phoneNum) async{

    print('-----------验证码获取-------------');
    Dio dio = Dio();
    int localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();


    int request_date = localDate - dateError;

    Map unsortMap = {
      'request_date': localDate - dateError,
      'uuid':uuid,
      'mobile':phoneNum,
    };

    var sortMap = unsortMap.keys.toList()..sort();

    print(sortMap);

    String MapCode = sortMap[0] + unsortMap[sortMap[0]].toString() + sortMap[1] + unsortMap[sortMap[1]].toString() + sortMap[2] + unsortMap[sortMap[2]].toString() + globals.appKey;
    print(MapCode);
    String autographCode = generateMd5(MapCode);

    print('request_time:${localDate - dateError}');
    print('uuid:${uuid}');
    print('手机号:${phoneNum.toString()}');
    print('签名:${autographCode}');

    final response = await dio.post(testURL+'/login/sendsms',
        data: {
          'request_date':localDate - dateError,
          'uuid':uuid,
          'mobile':phoneNum
        },
        options: Options(
            contentType:Headers.formUrlEncodedContentType,
            headers: {
              'BSAppID':globals.appID,
              'BSAuthSign':autographCode,
              'READING':'API',
              'Content-Type':'application/x-www-form-urlencoded'}));
    if(response.statusCode == 200)
    {
      return response.data;
    }
    else
    {
      print(response.statusCode);
      throw Exception('加载getAuthCode接口失败');
    }
  }

  static Future wechatLogin(int dateError, String code, String state) async{
    print('----------- 微信登录 ---------------');
    Dio dio = Dio();
    int localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();
    int request_date = localDate - dateError;
    Map unsortMap = {
      'request_date': request_date,
      'state': state,
      'code': code,
    };
    var sortMap = unsortMap.keys.toList()..sort();
    String MapCode = sortMap[0] + unsortMap[sortMap[0]].toString() + sortMap[1] + unsortMap[sortMap[1]].toString() + sortMap[2] + unsortMap[sortMap[2]].toString() + globals.appKey;
    print(MapCode);
    String autographCode = generateMd5(MapCode);
    final response = await dio.post(testURL+'/wechat/oauth/appcallback',
        data: {
          'request_date':localDate - dateError,
          'state':state,
          'code':code
        },
        options: Options(
            contentType:Headers.formUrlEncodedContentType,
            headers: {
              'BSAppID':globals.appID,
              'BSAuthSign':autographCode,
              'READING':'API',
              'Content-Type':'application/x-www-form-urlencoded'}));
    if(response.statusCode == 200)
    {
      return response.data;
    }
    else
    {
      print(response.statusCode);
      throw Exception('加载wechat登录接口失败');
    }
  }

  static Future goLogin(int dateError, String uuid, int phoneNum, int authCode) async{
    print('-----------登录-------------');
    Dio dio = Dio();
    int localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();

    int request_date = localDate - dateError;

    Map unsortMap = {
      'request_date': localDate - dateError,
      'uuid':uuid,
      'mobile':phoneNum,
      'authcode':authCode
    };

    var sortMap = unsortMap.keys.toList()..sort();

    print(sortMap);

    String MapCode = sortMap[0] + unsortMap[sortMap[0]].toString() + sortMap[1] + unsortMap[sortMap[1]].toString() + sortMap[2] + unsortMap[sortMap[2]].toString() + sortMap[3] + unsortMap[sortMap[3]].toString() + globals.appKey;
    print(MapCode);
    String autographCode = generateMd5(MapCode);

    print('验证码:${authCode.toString()}');
    print('request_time:${localDate - dateError}');
    print('uuid:${uuid}');
    print('手机号:${phoneNum.toString()}');
    print('签名:${autographCode}');

    final response = await dio.post(testURL+'/login/mobile',
        data: {
          'request_date':localDate - dateError,
          'uuid':uuid,
          'mobile':phoneNum,
          'authcode':authCode
        },
        options: Options(
            contentType:Headers.formUrlEncodedContentType,
            headers: {
              'BSAppID':globals.appID,
              'BSAuthSign':autographCode,
              'READING':'API',
              'Content-Type':'application/x-www-form-urlencoded'}));
    if(response.statusCode == 200)
    {
      return response.data;
    }
    else
    {
      print(response.statusCode);
      throw Exception('加载login接口失败');
    }
  }


  static Future fetchAppID(int dateError) async{
    print('-------- 获取微信AppID -----------');

    Dio dio = Dio();

    int localDate = ((DateTime.now().millisecondsSinceEpoch)~/1000).toInt();

    int request_date = localDate - dateError;

    Map unsortMap = {
      'request_date': request_date,
    };


    var sortMap = unsortMap.keys.toList()..sort();

    String MapCode = sortMap[0] + unsortMap[sortMap[0]].toString() + globals.appKey;
    String BSAuthSign = generateMd5(MapCode);


    print('request_date:${request_date}');
    print('签名：${BSAuthSign}');
    final response = await dio.post(testURL+'/wechat/oauth/appstate',
        data: {
          'request_date':request_date,
        },
        options: Options(
            contentType:Headers.formUrlEncodedContentType,
            headers: {
              'BSAppID':globals.appID,
              'BSAuthSign':BSAuthSign,
              'READING':'API',
              'Content-Type':'application/x-www-form-urlencoded'}));
    if(response.statusCode == 200)
    {
      return response.data;
    }
    else
    {
      print(response.statusCode);
      throw Exception('加载微信AppID接口失败');
    }
  }

  static Future fetchUserData(String sessionID) async{
    print('-----------获取用户信息-------------');
    Dio dio = Dio();

    final response = await dio.get(testURL+'/user/profile',
        options: Options(
            contentType:Headers.formUrlEncodedContentType,
            headers: {
              'BSAuthorization':sessionID,
              'READING':'API',
            }));
    if(response.statusCode == 200)
    {
      return response.data;
    }
    else
    {
      print(response.statusCode);
      throw Exception('加载userData接口失败');
    }
  }
}



generateMd5(String data) {
  var content = new Utf8Encoder().convert(data);
  var md5 = crypto.md5;
  var digest = md5.convert(content);
  return hex.encode(digest.bytes);
}